<template>
  <div class="app-container shop-detail page-shop-edit">
    <!-- 导航栏 -->
    <div class="nav-box">
      <div class="nav">
        <div
          :class="['nav-item', navStatus === 0 ? 'active' : '']"
          @click="switchNav(0)"
        >
          {{ $t('shopProcess.basicInfo') }}
        </div>
        <!-- <div
          :class="['nav-item', navStatus === 1 ? 'active' : '']"
          @click="switchNav(1)"
        >
          {{ $t('shopProcess.businessInfo') }}
        </div> -->
        <div
          :class="['nav-item', navStatus === 2 ? 'active' : '']"
          @click="switchNav(2)"
        >
          {{ $t('shopProcess.signUpInfo') }}
        </div>
        <div
          :class="['nav-item', navStatus === 3 ? 'active' : '']"
          @click="switchNav(3)"
        >
          {{ $t('shopProcess.financeInfo') }}
        </div>
      </div>
    </div>
    <!-- 模块 -->
    <div class="shop-info-box">
      <el-alert
        v-if="shopStatus.shopStatus===6&&(statusRemarks || modifyInformation.remarks)"
        :title="`您的开设商城申请未通过！原因是：${statusRemarks || modifyInformation.remarks}。`"
        type="error"
        show-icon
        style="margin-top: 20px;"
      />
      <!-- 基本信息 -->
      <div
        v-show="navStatus === 0"
        class="basic-info-mod"
      >
        <!-- 商城审核状态 -->
        <div class="audit-status">
          <!-- status 0 未审核 1已通过 -1未通过 2平台下线 3 平台下线待审核 -->
          <!-- shopStatus 商城状态(-1:已删除 0: 停业中 1:营业中 2:平台下线 3:待审核 4:商城申请中 5.审核失败 6.上线审核失败) -->

          <div
            v-if="shopAuditStatus"
            class="audit-item"
          >
            <span>{{ $t('shopProcess.auditStatus') }}：</span>
            <span v-if="shopAuditStatus.status === -1">{{ $t('shop.failed') }}</span>
            <span v-if="shopAuditStatus.status === 0">{{ $t('shop.unreviewed') }}</span>
            <span v-if="shopAuditStatus.status === 1">{{ $t('shop.passed') }}</span>
            <span v-if="shopAuditStatus.status === 2">{{ $t('shop.platformOffline') }}</span>
          </div>
          <div class="audit-item">
            <span>{{ $t('shopProcess.accountStatus') }}：</span>
            <span v-if="shopBasicInfo.accountStatus === 0">{{ $t('shopProcess.disable') }}</span>
            <span v-if="shopBasicInfo.accountStatus === 1">{{ $t('shopProcess.enable') }}</span>
            <span v-if="shopBasicInfo.accountStatus === -1">{{ $t('shopProcess.delete') }}</span>
          </div>
          <div class="audit-item">
            <span>{{ $t('shopProcess.shopStatus') }}：</span>
            <span v-if="shopBasicInfo.shopStatus === -1">{{ $t('shopProcess.deleted') }}</span>
            <span v-if="shopBasicInfo.shopStatus === 0">{{ $t('shopProcess.closed') }}</span>
            <span v-if="shopBasicInfo.shopStatus === 1">{{ $t('shopProcess.inOperation') }}</span>
            <span v-if="shopBasicInfo.shopStatus === 2">{{ $t('shop.platformOffline') }}</span>
            <span v-if="shopBasicInfo.shopStatus === 3">{{ $t('shopProcess.onlinePendingReview') }}</span>
            <span v-if="shopBasicInfo.shopStatus === 4">{{ $t('shopProcess.shopApplication') }}</span>
            <span v-if="shopBasicInfo.shopStatus === 5">{{ $t('shopProcess.storeOpenPendingReview') }}</span>
            <span v-if="paySettlementType===1 && shopBasicInfo.shopStatus === 6">上线审核失败</span>
          </div>
        </div>
        <!-- 信息 -->
        <div class="basic-info-list">
          <!-- 通联支付下平台开设商城且审核失败的商城不可更改基本信息 -->
          <el-form
            ref="shopBasicInfoRef"
            label-width="120px"
            :model="shopBasicInfo"
            :rules="shopBasicInfoRules"
            :disabled="paySettlementType===1 && shopStatus.shopStatus===6 && !signingInfo.contractStartTime"
            @submit.prevent
          >
            <!-- 商城信息 -->
            <el-divider content-position="left">
              {{ $t('pcdecorate.shopMessage.storeMessage') }}
            </el-divider>
            <div class="basic-info-box">
              <div class="left-info">
                <el-form-item
                  :label="$t('shopProcess.logo')"
                  prop="shopLogo"
                >
                  <div class="business-license-box">
                    <div class="license-content">
                      <img-upload v-model="shopBasicInfo.shopLogo" />
                    </div>
                    <div class="upload-tips">
                      {{ $t('shopProcess.logoTips') }}
                    </div>
                  </div>
                </el-form-item>

                <el-form-item
                  :label="$t('shopProcess.shopName')"
                  prop="shopName"
                >
                  <p class="txt">
                    <el-input
                      v-model="shopBasicInfo.shopName"
                      :placeholder="$t('shopProcess.shopNameInputTips')"
                      maxlength="20"
                      @blur="
                        shopBasicInfo.shopName =
                          shopBasicInfo.shopName ?
                            removeHeadAndTailSpaces(shopBasicInfo.shopName) :
                            shopBasicInfo.shopName
                      "
                    />
                  </p>
                </el-form-item>

                <el-form-item
                  label="商城首字母"
                  prop="firstLetter"
                >
                  <p class="txt">
                    <el-input
                      v-model="shopBasicInfo.firstLetter"
                      placeholder="请输入商城首字母"
                      maxlength="1"
                      show-word-limit
                      @blur="
                        shopBasicInfo.firstLetter =
                          shopBasicInfo.firstLetter ?
                            removeHeadAndTailSpaces(shopBasicInfo.firstLetter) :
                            shopBasicInfo.firstLetter
                      "
                    />
                  </p>
                </el-form-item>

                <el-form-item
                  label="商城供应商"
                  prop="shopSupplier"
                >
                  <p class="txt">
                    <el-input
                      v-model="shopBasicInfo.shopSupplier"
                      placeholder="请输入商城供应商"
                      maxlength="20"
                      show-word-limit
                      @blur="
                        shopBasicInfo.shopSupplier =
                          shopBasicInfo.shopSupplier ?
                            removeHeadAndTailSpaces(shopBasicInfo.shopSupplier) :
                            shopBasicInfo.shopSupplier
                      "
                    />
                  </p>
                </el-form-item>

                <el-form-item
                  :label="$t('shopProcess.intro')"
                  prop="intro"
                >
                  <div
                    class="business-license-box"
                    style="width: 100%"
                  >
                    <div class="license-content">
                      <el-input
                        v-model="shopBasicInfo.intro"
                        type="textarea"
                        :rows="4"
                        maxlength="200"
                        :placeholder="$t('shopProcess.introInput')"
                        @blur="
                          shopBasicInfo.intro =
                            shopBasicInfo.intro ?
                              removeHeadAndTailSpaces(shopBasicInfo.intro) :
                              shopBasicInfo.intro
                        "
                      />
                    </div>
                  </div>
                </el-form-item>
              </div>
            </div>

            <!-- 商家信息 -->
            <el-divider content-position="left">
              {{ $t('shopProcess.merchantInfo') }}
            </el-divider>
            <div class="basic-info-box">
              <div class="left-info">
                <el-form-item
                  :label="$t('shopProcess.merchantLogo')"
                  prop="merchantLogo"
                >
                  <div class="business-license-box">
                    <div class="license-content">
                      <img-upload
                        v-model="companyInfo.merchantLogo"
                        disabled
                      />
                    </div>
                    <div class="upload-tips">
                      {{ $t('shopProcess.logoTips') }}
                    </div>
                  </div>
                </el-form-item>

                <el-form-item
                  :label="$t('shopProcess.merchantName')"
                  prop="merchantName"
                >
                  <p class="txt">
                    {{ companyInfo.merchantName }}
                    <!-- <el-input
                      v-model="companyInfo.merchantName"
                      :placeholder="$t('shopProcess.merchantNameInputTips')"
                      maxlength="50"
                      @blur="
                        companyInfo.merchantName =
                          companyInfo.merchantName ?
                            removeHeadAndTailSpaces(companyInfo.merchantName) :
                            companyInfo.merchantName
                      "
                    /> -->
                  </p>
                </el-form-item>

                <el-form-item
                  :label="$t('shopProcess.merchantShortName')"
                  prop="merchantShortName"
                >
                  <p class="txt">
                    {{ companyInfo.merchantShortName }}
                    <!-- <el-input
                      v-model="companyInfo.merchantShortName"
                      :placeholder="$t('shopProcess.merchantShortNameInputTips')"
                      maxlength="10"
                      @blur="
                        companyInfo.merchantShortName =
                          companyInfo.merchantShortName ?
                            removeHeadAndTailSpaces(companyInfo.merchantShortName) :
                            companyInfo.merchantShortName
                      "
                    /> -->
                  </p>
                </el-form-item>

                <el-form-item
                  :label="$t('shopProcess.mainProduct')"
                  prop="mainProduct"
                >
                  <p class="txt">
                    {{ companyInfo.mainProduct }}
                    <!-- <el-input
                      v-model="companyInfo.mainProduct"
                      :placeholder="$t('shopProcess.mainProductsInputTips')"
                      maxlength="500"
                      show-word-limit
                      @blur="
                        companyInfo.mainProduct =
                          companyInfo.mainProduct ?
                            removeHeadAndTailSpaces(companyInfo.mainProduct) :
                            companyInfo.mainProduct
                      "
                    /> -->
                  </p>
                </el-form-item>

                <el-form-item
                  :label="$t('shopProcess.tel')"
                  prop="tel"
                >
                  <p class="txt">
                    {{ shopBasicInfo.tel }}
                    <!-- <el-input
                      v-model="shopBasicInfo.tel"
                      maxlength="11"
                      :placeholder="$t('shopProcess.telInputTips')"
                    /> -->
                  </p>
                </el-form-item>

                <!-- 商家电话 -->
                <el-form-item
                  :label="$t('shopProcess.merchantPhone')"
                  prop="merchantPhone"
                >
                  <p class="txt">
                    {{ companyInfo.merchantPhone }}
                    <!-- <el-input
                      v-model="companyInfo.merchantPhone"
                      :placeholder="$t('tip.input') + $t('shopProcess.merchantPhone')"
                      oninput="value=value.replace(/[^\d\-\d]/g,'')"
                    /> -->
                  </p>
                </el-form-item>

                <el-form-item
                  :label="$t('sys.email')"
                  prop="merchantMail"
                >
                  <p class="txt">
                    {{ companyInfo.merchantMail }}
                    <!-- <el-input
                      v-model="companyInfo.merchantMail"
                      :placeholder="$t('tip.input') + $t('sys.email')"
                      @blur="
                        companyInfo.merchantMail =
                          companyInfo.merchantMail ?
                            removeHeadAndTailSpaces(companyInfo.merchantMail) :
                            companyInfo.merchantMail
                      "
                    /> -->
                  </p>
                </el-form-item>

                <el-form-item
                  :label="$t('shopProcess.officeWeb')"
                  prop="merchantWebsite"
                >
                  <p class="txt">
                    {{ companyInfo.merchantWebsite }}
                    <!-- <el-input
                      v-model="companyInfo.merchantWebsite"
                      :placeholder="$t('tip.input') + $t('shopProcess.officeWeb')"
                      maxlength="100"
                      @blur="
                        companyInfo.merchantWebsite =
                          companyInfo.merchantWebsite ?
                            removeHeadAndTailSpaces(companyInfo.merchantWebsite) :
                            companyInfo.merchantWebsite
                      "
                    /> -->
                  </p>
                </el-form-item>

                <el-form-item
                  :label="$t('shopProcess.companyAdv')"
                  prop="merchantSlogan"
                >
                  <div
                    class="business-license-box"
                    style="width: 100%"
                  >
                    <div
                      class="license-content"
                      style="word-break: break-all;"
                    >
                      {{ companyInfo.merchantSlogan }}
                      <!-- <el-input
                        v-model="companyInfo.merchantSlogan"
                        type="textarea"
                        :rows="4"
                        maxlength="200"
                        show-word-limit
                        :placeholder="$t('tip.input') + $t('shopProcess.companyAdv')"
                        @blur="
                          companyInfo.merchantSlogan =
                            companyInfo.merchantSlogan ?
                              removeHeadAndTailSpaces(companyInfo.merchantSlogan) :
                              companyInfo.merchantSlogan
                        "
                      /> -->
                    </div>
                  </div>
                </el-form-item>
              </div>
              <div class="right-info">
                <el-form-item
                  :label="$t('shopProcess.companyPic')"
                  prop="promotionalImg"
                >
                  <div class="business-license-box">
                    <div class="license-content">
                      <img-upload
                        v-model="companyInfo.promotionalImg"
                        disabled
                      />
                    </div>
                    <div class="upload-tips">
                      {{ $t('shopProcess.logoTips') }}
                    </div>
                  </div>
                </el-form-item>
              </div>
            </div>
          </el-form>
        </div>

        <div
          v-if="paySettlementType!==1 || (paySettlementType===1 && !(shopStatus.shopStatus===6&&!signingInfo.contractStartTime))"
          class="default-btn primary-btn foot-btn"
          @click="updateShopBasicInfo"
        >
          {{ $t('shopProcess.saveBasicInfo') }}
        </div>
      </div>
      <!-- /基本信息 -->

      <!-- 工商信息 -->
      <div
        v-show="navStatus === 1"
        class="business-info-mod"
      >
        <!-- 开启通联支付后，平台只能修改没有签约日期的审核失败的自营商城 -->
        <el-form
          ref="companyInfoFormRef"
          :model="companyInfoForm"
          :rules="companyInfoRule"
          :label-width="lang === 'en' ? '200px' : '150px'"
          :disabled="paySettlementType === 1 && !(shopStatus.shopStatus===6 && signingInfo.type===1 && !signingInfo.contractStartTime)"
          @submit.prevent
        >
          <div class="ci-wrapper">
            <div class="left-info">
              <el-form-item
                :label="$t('shopProcess.creditCode')"
                prop="creditCode"
              >
                <el-input
                  v-model="companyInfoForm.creditCode"
                  maxlength="20"
                  :placeholder="$t('shopProcess.creditCodeInputTips')"
                />
              </el-form-item>
              <el-form-item
                :label="$t('shopProcess.firmName')"
                prop="firmName"
              >
                <el-input
                  v-model="companyInfoForm.firmName"
                  maxlength="50"
                  :placeholder="$t('shopProcess.firmNameInputTips')"
                  @blur="
                    companyInfoForm.firmName =
                      companyInfoForm.firmName ?
                        removeHeadAndTailSpaces(companyInfoForm.firmName) :
                        companyInfoForm.firmName
                  "
                />
              </el-form-item>
              <el-form-item
                :label="$t('shopProcess.residence')"
                prop="residence"
              >
                <el-input
                  v-model="companyInfoForm.residence"
                  maxlength="50"
                  :placeholder="$t('shopProcess.residenceInputTips')"
                  @blur="
                    companyInfoForm.residence =
                      companyInfoForm.residence ?
                        removeHeadAndTailSpaces(companyInfoForm.residence) :
                        companyInfoForm.residence
                  "
                />
              </el-form-item>
              <el-form-item
                :label="$t('shopProcess.representative')"
                prop="representative"
              >
                <el-input
                  v-model="companyInfoForm.representative"
                  prop="representative"
                  maxlength="20"
                  :placeholder="$t('shopProcess.representativeInputTips')"
                  @blur="
                    companyInfoForm.representative =
                      companyInfoForm.representative ?
                        removeHeadAndTailSpaces(companyInfoForm.representative) :
                        companyInfoForm.representative
                  "
                />
              </el-form-item>
              <el-form-item
                v-if="paySettlementType===1"
                label="法人身份证号"
                prop="legalIds"
              >
                <el-input
                  v-model="companyInfoForm.legalIds"
                  maxlength="18"
                  placeholder="输入法人身份证号"
                />
              </el-form-item>
              <el-form-item
                v-if="paySettlementType===1"
                label="法人手机号"
                prop="legalPhone"
              >
                <el-input
                  v-model="companyInfoForm.legalPhone"
                  maxlength="11"
                  placeholder="输入法人手机号"
                  @input="(val)=>{companyInfoForm.legalPhone=val.replace(/[^\d]/g,'')}"
                />
              </el-form-item>
              <el-form-item :label="$t('shopProcess.capital')">
                <div class="capital-int">
                  <el-input
                    v-model="companyInfoForm.capital"
                    prop="capital"
                    :min="0"
                    :max="99999999"
                    @blur="changeNum"
                    @keydown="channelInputLimit"
                  >
                    <template #append>
                      <el-button>
                        {{ $t("shopProcess.tenThousandYuan") }}
                      </el-button>
                    </template>
                  </el-input>
                </div>
              </el-form-item>
              <el-form-item
                :label="$t('shopProcess.fountTime')"
                prop="foundTime"
              >
                <el-date-picker
                  v-model="companyInfoForm.foundTime"
                  type="date"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('platform.seleData')"
                  :picker-options="pickerOptions"
                />
              </el-form-item>
              <el-form-item
                :label="$t('shopProcess.businessTime')"
                prop="startTime"
              >
                <div style="display: flex">
                  <el-date-picker
                    v-model="companyInfoForm.startTime"
                    style="width:162px;"
                    type="date"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :placeholder="$t('shopProcess.startTime')"
                    clearable
                    @change="onValidateTime('startTime')"
                  />
                  <span style="margin: 0 10px">-</span>
                  <span class="end-time">
                    <el-date-picker
                      ref="endTimeRef"
                      v-model="companyInfoForm.endTime"
                      style="width:162px;"
                      type="date"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :placeholder="(endTimeFlag && !companyInfoForm.endTime && companyInfoForm.startTime) ? '' : $t('shopProcess.endTime')"
                      clearable
                      :disabled="!companyInfoForm.startTime"
                      @change="onValidateTime('endTime')"
                      @focus="endTimeFlag = false"
                      @blur="endTimeFlag = true"
                    />
                    <span
                      v-if="endTimeFlag && !companyInfoForm.endTime && companyInfoForm.startTime"
                      class="text"
                      @click="focusEndTime"
                    >
                      {{ $t('shopProcess.noFixedTerm') }}
                    </span>
                  </span>
                </div>
              </el-form-item>
              <el-form-item
                :label="$t('shopProcess.businessScope')"
                prop="businessScope"
              >
                <el-input
                  v-model="companyInfoForm.businessScope"
                  type="textarea"
                  resize="none"
                  :rows="4"
                  :placeholder="$t('shopProcess.businessScopeInputTips')"
                  maxlength="500"
                  @blur="
                    companyInfoForm.businessScope =
                      companyInfoForm.businessScope ?
                        removeHeadAndTailSpaces(companyInfoForm.businessScope) :
                        companyInfoForm.businessScope
                  "
                />
              </el-form-item>
            </div>
            <div class="right-info">
              <el-form-item
                :label="$t('shopProcess.businessLicense')"
                label-width="150px"
                prop="businessLicense"
              >
                <div class="business-license-box">
                  <div class="license-content">
                    <div class="upload-img-box">
                      <div
                        v-if="paySettlementType === 1 && !(shopBasicInfo.shopStatus===6 && signingInfo.type===1 && !signingInfo.contractStartTime)"
                        class="mask"
                      />
                      <img-upload v-model="companyInfoForm.businessLicense" />
                    </div>
                    <div class="example-box">
                      <img
                        src="@/assets/img/example-img/Business-license.png"
                        alt
                      >
                      <div class="tips">
                        {{ $t('shopProcess.example') }}
                      </div>
                    </div>
                  </div>
                  <div class="upload-tips">
                    {{ $t('shopProcess.logoTips') }}
                  </div>
                </div>
              </el-form-item>
              <div class="id-box">
                <div class="upload-content">
                  <div
                    class="upload-img"
                    :class="lang === 'en' ? 'en-upload-img' : 'zh-upload-img'"
                  >
                    <el-form-item
                      class="idcard"
                      :label="$t('shopProcess.corporateIdentityCard')"
                      label-width="150px"
                      prop="identityCardFront"
                    >
                      <div class="upload-img-box">
                        <div
                          v-if="paySettlementType === 1 && !(shopBasicInfo.shopStatus===6 && signingInfo.type===1 && !signingInfo.contractStartTime)"
                          class="mask"
                        />
                        <img-upload
                          v-model="companyInfoForm.identityCardFront"
                        />
                      </div>
                    </el-form-item>
                    <el-form-item
                      class="idcard"
                      label-width="0"
                      prop="identityCardLater"
                    >
                      <div class="upload-img-box">
                        <div
                          v-if="paySettlementType === 1 && !(shopBasicInfo.shopStatus===6 && signingInfo.type===1 && !signingInfo.contractStartTime)"
                          class="mask"
                        />
                        <img-upload
                          v-model="companyInfoForm.identityCardLater"
                        />
                      </div>
                    </el-form-item>
                  </div>
                  <div class="upload-example">
                    <div class="example-box">
                      <img
                        src="@/assets/img/example-img/idcard1.png"
                        alt
                      >
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        :content="$t('shopProcess.identityCardFront')"
                        placement="bottom"
                      >
                        <div class="tips">
                          {{ $t('shopProcess.identityCardFront') }}
                        </div>
                      </el-tooltip>
                    </div>
                    <div class="example-box">
                      <img
                        src="@/assets/img/example-img/idcard2.png"
                        alt
                      >
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        :content="$t('shopProcess.identityCardLater')"
                        placement="bottom"
                      >
                        <div class="tips">
                          {{ $t('shopProcess.identityCardLater') }}
                        </div>
                      </el-tooltip>
                    </div>
                  </div>
                  <div class="upload-tips">
                    {{ $t('shopProcess.identityCardTips') }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form>

        <div
          v-if="paySettlementType!==1 || (paySettlementType===1 && shopStatus.shopStatus===6 && signingInfo.type===1 && !signingInfo.contractStartTime)"
          class="default-btn primary-btn"
          :class="lang === 'en' ? 'en-foot-btn' : 'foot-btn'"
          @click="updateCompanyInfo"
        >
          {{ $t('shopProcess.saveCompanyInfo') }}
        </div>
      </div>
      <!-- /工商信息 -->

      <!-- 签约信息 -->
      <div
        v-show="navStatus === 2"
        class="contract-info table-box"
      >
        <!-- 签约类目 -->
        <div class="s-category-item s-item">
          <div class="table-data-title">
            <div class="text">
              <span class="stress">*</span>{{ $t('shopProcess.signingCategory') }}
            </div>
            <div class="tips">
              {{ $t('shopProcess.preSigned') }}
              <span class="txt-bold">{{ signCategoryList.length }}</span>
              {{ $t('shopProcess.piece') }}{{ $t('shopProcess.category') }}，
              {{ $t('shopProcess.mostAdd') }}
              <span class="txt-bold">200</span>
              {{ $t('shopProcess.piece') }}{{ $t('shopProcess.category') }}
            </div>
            <div
              v-if="paySettlementType!==1||(paySettlementType===1&&!(shopStatus.shopStatus===6 && !signingInfo.contractStartTime))"
              class="edit-btn"
            >
              <div
                class="default-btn primary-btn"
                @click="addSigningHandle(0)"
              >
                {{ $t('shopProcess.addSigningCategory') }}
              </div>
              <div
                class="default-btn primary-btn"
                @click="cateAddOrUpdateHandle(0)"
              >
                {{ $t('shopProcess.editSigningCategory') }}
              </div>
            </div>
          </div>
          <div class="si-content">
            <el-table
              :data="signCategoryList"
              header-cell-class-name="table-header"
              style="width: 100%"
            >
              <el-table-column
                prop="name"
                :label="$t('shopProcess.categoryName')"
              />
              <el-table-column
                prop="parentName"
                :label="$t('shopProcess.parentCategoryName')"
              />
              <el-table-column
                prop="platformRate"
                :label="$t('shopProcess.categoryRate')"
              >
                <template #default="{ row }">
                  <span v-if="row.platformRate || row.platformRate === 0">{{ row.platformRate }} %</span>
                  <span v-else>--</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="customizeRate"
                :label="$t('shopProcess.customRate')"
              >
                <template #default="{ row }">
                  <span v-if="row.customizeRate || row.customizeRate === 0">{{ row.customizeRate }} %</span>
                  <span v-else>--</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="qualifications"
                :label="$t('shopProcess.categoryQualifications')"
              >
                <template #default="{row}">
                  <div
                    v-if="row.imgs.length"
                    class="img-box"
                  >
                    <el-image
                      v-for="(img,index) in row.imgs"
                      :key="index"
                      class="tab-img"
                      :src="checkFileUrl(img)"
                      fit="cover"
                      preview-teleported
                      :preview-src-list="checkFileUrl(row.imgs)"
                      :initial-index="initialIndex"
                      @click="initialIndex=index"
                    />
                  </div>
                  <span v-if="!row.imgs.length">--</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="categoryStatus"
                :label="$t('shopProcess.categoryStatus')"
              >
                <template #default="scope">
                  <div
                    v-if="scope.row.categoryStatus === 1"
                    class="tag-txt"
                  >
                    {{ $t('publics.normal') }}
                  </div>
                  <div
                    v-if="scope.row.categoryStatus === 0"
                    class="tag-txt red-tag-txt"
                  >
                    {{ $t('publics.LowerShelf') }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 签约品牌 -->
        <div class="s-brand-item s-item">
          <div class="table-data-title">
            <div class="text">
              {{ $t('shopProcess.signingBrand') }}
            </div>
            <div class="tips">
              {{ $t('shopProcess.preSigned') }}
              <span class="txt-bold">{{ signedBrands.length }}</span>
              {{ $t('shopProcess.piece') }}{{ $t('shopProcess.brand') }}，
              {{ $t('shopProcess.mostAdd') }}
              <span class="txt-bold">50</span>
              {{ $t('shopProcess.piece') }}{{ $t('shopProcess.brand') }}
            </div>
            <div
              v-if="paySettlementType!==1||(paySettlementType===1&&!(shopStatus.shopStatus===6 && !signingInfo.contractStartTime))"
              class="edit-btn"
            >
              <div
                class="default-btn primary-btn"
                @click="addSigningHandle(1)"
              >
                {{ $t('shopProcess.addSigningBrand') }}
              </div>
              <div
                class="default-btn primary-btn"
                @click="cateAddOrUpdateHandle(1)"
              >
                {{ $t('shopProcess.editSigningBrand') }}
              </div>
            </div>
          </div>
          <div class="si-content main-container">
            <div class="table-con">
              <el-table
                :data="signedBrands"
                header-cell-class-name="table-header"
                style="width: 100%"
              >
                <el-table-column
                  prop="name"
                  :label="$t('shopProcess.brandName')"
                >
                  <template #default="scope">
                    <span class="table-cell-text">{{ scope.row.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="firstLetter"
                  :label="$t('shopProcess.firstLetter')"
                />
                <el-table-column
                  prop="platformRate"
                  :label="$t('shopProcess.brandLogo')"
                >
                  <template #default="scope">
                    <div class="brand-logo">
                      <el-image
                        v-if="scope.row.imgUrl"
                        class="tab-img"
                        fit="cover"
                        preview-teleported
                        :src="checkFileUrl(scope.row.imgUrl)"
                        :preview-src-list="[checkFileUrl(scope.row.imgUrl)]"
                      />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="imgs"
                  :label="$t('shopProcess.brandQualifications')"
                >
                  <template #default="{row}">
                    <div
                      v-if="row.imgs.length"
                      class="brand-logo"
                    >
                      <el-image
                        v-for="(img,index) in row.imgs"
                        :key="index"
                        class="tab-img"
                        :src="checkFileUrl(img)"
                        fit="cover"
                        preview-teleported
                        :preview-src-list="checkFileUrl(row.imgs)"
                        :initial-index="initialIndex"
                        @click="initialIndex=index"
                      />
                    </div>
                    <div v-if="!row.imgs.length">
                      --
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="brandStatus"
                  :label="$t('shopProcess.brandStatus')"
                >
                  <template #default="scope">
                    <div
                      v-if="scope.row.brandStatus === 1"
                      class="tag-txt"
                    >
                      {{ $t('publics.normal') }}
                    </div>
                    <div
                      v-if="scope.row.brandStatus === 0"
                      class="tag-txt red-tag-txt"
                    >
                      {{ $t('publics.LowerShelf') }}
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <!-- 试用 -->
        <div class="s-sign-item s-item">
          <div class="table-data-title">
            <div class="text">
              <span class="stress">*</span>是否试用
            </div>
          </div>
          <div class="si-content">
            <div>
              <el-radio
                v-model="signingInfo.hasTry"
                :label="1"
                @click="onChangeUse(1, signingInfo.hasTry)"
              >
                {{ $t('publics.yes') }}
              </el-radio>
              <el-radio
                v-model="signingInfo.hasTry"
                :label="0"
                @click="onChangeUse(0, signingInfo.hasTry)"
              >
                {{ $t('publics.no') }}
              </el-radio>
            </div>
          </div>
        </div>
        <!-- 版本 -->
        <div class="s-sign-item s-item">
          <div class="table-data-title">
            <div class="text">
              <span class="stress">*</span>商城版本
            </div>
          </div>
          <div class="si-content">
            <div>
              <el-radio
                v-model="signingInfo.mallVersion"
                :disabled="signingInfo.hasTry==1"
                :label="1"
                @click="onChangeVer(1, signingInfo.mallVersion)"
              >
                免费版
              </el-radio>
              <el-radio
                v-model="signingInfo.mallVersion"
                :disabled="signingInfo.hasTry==1"
                :label="2"
                @click="onChangeVer(2, signingInfo.mallVersion)"
              >
                基础版
              </el-radio>
              <el-radio
                v-model="signingInfo.mallVersion"
                :disabled="signingInfo.hasTry==1"
                :label="3"
                @click="onChangeVer(3, signingInfo.mallVersion)"
              >
                标准版
              </el-radio>
            </div>
          </div>
        </div>
        <!-- 签约有效期 -->
        <div
          v-if="paySettlementType!==1"
          class="s-sign-item s-item"
        >
          <div class="table-data-title">
            <div class="text">
              <span
                class="stress"
              >*</span>{{ $t('shopProcess.validityPeriodOfContract') }}
            </div>
            <div class="tips">
              {{ $t('shopProcess.validPeriod') }}
            </div>
          </div>
          <div class="si-content">
            <div class="contract-time-box">
              <el-date-picker
                v-model="signingInfo.contractStartTime"
                style="width:170px;"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('shopProcess.startTime')"
                :clearable="false"
              />
              <span style="margin: 0 10px">-</span>
              <div class="end-time">
                <el-date-picker
                  ref="contractEndTimeRef"
                  v-model="signingInfo.contractEndTime"
                  style="width:170px;"
                  type="date"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="contractEndTimeFlag &&signingInfo.contractStartTime&& !signingInfo.contractEndTime ? '' : $t('shopProcess.endTime')"
                  clearable
                  @change="contractEndTimeFlag = false,contractEndTimeChange($event)"
                  @focus="contractEndTimeFlag = false"
                  @blur="contractEndTimeFlag = true"
                />
                <span
                  v-if="contractEndTimeFlag && signingInfo.contractStartTime&& !signingInfo.contractEndTime"
                  class="text"
                  @click="focusEndTime"
                >
                  {{ $t('shopProcess.noFixedTerm') }}
                </span>
              </div>
            </div>
          </div>
        </div>
        <!-- 商家类型 -->
        <div class="s-sign-item s-item">
          <div class="table-data-title">
            <div class="text">
              <span class="stress">*</span>{{ $t('shopProcess.shopType') }}
            </div>
          </div>
          <div class="si-content">
            <div>
              <el-radio
                v-model="signingInfo.type"
                :disabled="paySettlementType===1 || signingInfo.hasTry==1 || signingInfo.mallVersion!=3"
                :label="0"
              >
                {{ $t('shopProcess.ordinaryShop') }}
              </el-radio>
              <el-radio
                v-model="signingInfo.type"
                :disabled="paySettlementType===1 || signingInfo.hasTry==1 || signingInfo.mallVersion!=3"
                :label="1"
              >
                {{ $t('shopProcess.preferredGoodShop') }}
              </el-radio>
            </div>
          </div>
        </div>
        <div
          v-if="paySettlementType!==1 || (paySettlementType===1 && !(shopStatus.shopStatus===6&&!signingInfo.contractStartTime))"
          class="default-btn primary-btn foot-btn"
          @click="updateSigningInfo"
        >
          {{ $t('shopProcess.saveContractInformation') }}
        </div>
      </div>
      <!-- /签约信息 -->

      <!-- 财务信息 -->
      <div
        v-show="navStatus === 3"
        class="financial-info"
      >
        <div class="table-data-title">
          <div class="text">
            <span class="asterisk">*</span>{{ $t('shopProcess.settlementAccount') }}
          </div>
          <div
            v-if="paySettlementType!==1"
            class="tips"
          >
            {{ $t('shopProcess.added') }}
            <span class="txt-bold">{{ settlementAccounts.length }}</span>
            {{ $t('shopProcess.piece') }}{{ $t('shopProcess.settlementAccount') }},{{ $t('shopProcess.mostAdd') }}
            <span class="txt-bold">5</span>
            {{ $t('shopProcess.piece') }}{{ $t('shopProcess.settlementAccount') }}
          </div>
          <div
            v-if="paySettlementType===1 && shopStatus.shopStatus!==6"
            class="tips"
          >
            已添加
            <span class="txt-bold">{{ settlementAccounts.length }}</span>
            个结算账户，最多可添加
            <span class="txt-bold">10</span>
            个结算账户
            <span>
              ，
              <span class="txt-bold">1</span>
              个法人账户
            </span>
          </div>
          <div
            v-else-if="paySettlementType===1"
            class="tips"
          >
            请添加1个对公账户
          </div>
        </div>
        <div class="table-box">
          <el-table
            v-if="shopStatus.shopStatus!==6 && paySettlementType===1 || paySettlementType!==1"

            :data="settlementAccounts"
            header-cell-class-name="table-header"
            style="width: 100%"
          >
            <el-table-column
              prop="bankName"
              :label="$t('shopProcess.bankName')"
            />
            <el-table-column
              align="left"
              :min-width="paySettlementType===1?'130':null"
              prop="recipientName"
              :label="$t('shopProcess.recipientName')"
            >
              <template #default="scope">
                <div class="recipient-name">
                  <span>{{ scope.row.recipientName }}</span>
                  <div
                    v-if="paySettlementType===1&&scope.row.bankCardPro===0"
                    class="tip"
                  >
                    法人账户
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              align="left"
              :prop="paySettlementType===1?'bankCardNo':'cardNo'"
              :label="$t('shopProcess.account')"
            />
            <el-table-column
              prop="openingBank"
              :label="$t('shopProcess.openingBank')"
            />
            <el-table-column
              prop="isDefault"
              :label="$t('shopProcess.masterAccount')"
              align="center"
            >
              <template #default="scope">
                {{ scope.row.isDefault ? $t('shopProcess.yes') : $t('shopProcess.no') }}
              </template>
            </el-table-column>
          </el-table>
          <!-- 通联支付开启且平台开设商城审核失败则需要重新提交 -->
          <el-form
            v-if="shopStatus.shopStatus===6 && paySettlementType===1"
            ref="bankCartInfoFormRef"
            :model="bankCartInfoForm"
            :rules="bankCartInfoForm.rule"
            size="small"
            @submit.prevent
          >
            <el-table
              ref="bankTable"
              class="add-bank-info-table"
              :data="bankCartInfoForm.data"
              :header-cell-style="{height:'50px',background:'#F5F5F5',color:'#000','font-weight': '400'}"
              style="width: 100%"
            >
              <el-table-column
                type="index"
                label="序号"
                width="80"
              />
              <el-table-column
                prop="parentBankName"
                label="银行名称"
              >
                <template #default="scope">
                  <el-form-item
                    :prop="'data.' + scope.$index + '.parentBankName'"
                    :rules="bankCartInfoForm.rule.parentBankName"
                  >
                    <el-select
                      v-model="selectBank"
                      filterable
                      placeholder="请选择"
                      style="width:200px"
                      @change="changeBank"
                    >
                      <el-option
                        v-for="item in bankList"
                        :key="item.bankId"
                        :label="item.bankName"
                        :value="item.bankName"
                      />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="bankName"
                label="开户分行名称"
              >
                <template #default="scope">
                  <el-form-item
                    :prop="'data.' + scope.$index + '.bankName'"
                    :rules="bankCartInfoForm.rule.bankName"
                  >
                    <el-input
                      v-model="scope.row.bankName"
                      maxlength="20"
                      placeholder="例如：南京市雨花区雨花支行"
                      style="width:200px"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="accountNo"
                label="企业对公账户"
              >
                <template #default="scope">
                  <el-form-item
                    :prop="'data.' + scope.$index + '.accountNo'"
                    :rules="bankCartInfoForm.rule.accountNo"
                  >
                    <el-input
                      v-model.trim="scope.row.accountNo"
                      maxlength="19"
                      oninput="value=value.replace(/[^\d]/g,'')"
                      placeholder="请输入企业对公账户"
                      style="width:200px"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="unionBank"
                label="支付行号"
              >
                <template #default="scope">
                  <el-form-item
                    :prop="'data.' + scope.$index + '.unionBank'"
                    :rules="bankCartInfoForm.rule.unionBank"
                  >
                    <el-input
                      v-model="scope.row.unionBank"
                      placeholder="请输入12位的支付行号"
                      oninput="value=value.replace(/[^\d]/g,'')"
                      maxlength="12"
                      style="width:200px"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
          <!-- 通联支付开启时没有签约时间的自营商城开设商城审核失败则需要重新提交 -->
          <div
            v-if="paySettlementType === 1 && shopStatus.shopStatus===6 && signingInfo.type===1 && !signingInfo.contractStartTime"
            class="footer"
          >
            <div class="foot-box">
              <div
                class="btn"
                @click="toNextStep"
              >
                提交
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- /财务信息 -->
    </div>

    <category-add-or-update
      v-if="cateAddOrUpdateVisible"
      ref="cateAddOrUpdateRef"
      :sign-category-list="signCategoryList"
      @close-popup="closePopup"
    />
    <brand-add-or-update
      v-if="brandAddOrUpdateVisible"
      ref="brandAddOrUpdateRef"
      @close-popup="closePopup"
    />
    <!-- 类目签约弹窗 -->
    <add-signing-category
      v-if="addSigningCategoryVisible"
      ref="addSigningCategoryRef"
      :apply-for-sign="true"
      :signing-count="signCategoryList.length"
      @close-popup="closePopup"
    />
    <!-- 品牌签约弹窗 -->
    <add-signing-brand
      v-if="addSigningBrandVisible"
      ref="addSigningBrandRef"
      :apply-for-sign="true"
      :signing-count="signedBrands.length"
      @close-popup="closePopup"
    />
  </div>
</template>

<script setup>
import addSigningCategory from '../components/signing-components/category-add-or-update/index.vue'
import addSigningBrand from '../components/signing-components/brand-add-or-update/index.vue'
import { isCreditCode, validNoEmptySpace, removeHeadAndTailSpaces, checkIDCard, isTel } from '@/utils/validate.js'
import categoryAddOrUpdate from '../components/shop-edit/category-add-or-update/index.vue'
import brandAddOrUpdate from '../components/shop-edit/brand-add-or-update/index.vue'
import moment from 'moment'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()

const initialIndex = ref(0) // 图片预览索引

// 语言
const lang = ref(window.localStorage.getItem('bbcLang'))

// 商城状态
const shopStatus = ref({})

// 商城工商信息
const companyInfoForm = ref({
  creditCode: '',
  firmName: '',
  residence: '',
  representative: '',
  capital: '',
  foundTime: '',
  startTime: '',
  endTime: '',
  businessLicense: '',
  identityCardFront: '',
  identityCardLater: '',
  legalIds: '',
  legalPhone: ''
})

const modifyInformation = ref({
  creditCode: '',
  firmName: '',
  representative: '',
  capital: '',
  residence: '',
  foundTime: '',
  startTime: '',
  endTime: '',
  businessScope: '',
  businessLicense: '',
  identityCardFront: '',
  identityCardLater: '',
  remarks: ''
})
const validateMobile = (rule, value, callback) => {
  const phoneReg = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/
  const mobile = /^(?:(?:\+|00)86)?1\d{2}([\d*]{4})\d{4}$/
  if (phoneReg.test(value) || mobile.test(value)) {
    callback()
  } else {
    callback(new Error($t('shopProcess.telErrorTips')))
  }
}

const vaildCreditCode = (rule, value, callback) => {
  if (!isCreditCode(value)) {
    callback(new Error($t('shopProcess.creditCodeErrorTips')))
  } else {
    callback()
  }
}

const validateNotEmpty = (role, value, callback) => {
  if (validNoEmptySpace(value)) {
    callback(new Error($t('shopProcess.inputAllSpace')))
  } else {
    callback()
  }
}

// eslint-disable-next-line no-unused-vars
const validateNotEmptyRep = (role, value, callback) => {
  companyInfoForm.value.representative = companyInfoForm.value.representative.trim()
  if (companyInfoForm.value.representative === '' || companyInfoForm.value.representative.indexOf(' ') !== -1) {
    callback(new Error($t('shopProcess.inputAllSpace')))
  } else {
    callback()
  }
}

const validIDCard = (rule, value, callback) => {
  if (!value || !checkIDCard(value)) {
    callback(new Error('请输入正确的法人身份证'))
  } else {
    callback()
  }
}

const validateEmail = (rule, value, callback) => {
  if (!value) callback()
  if (!validEmail(value) || value.indexOf(' ') !== -1) {
    callback(new Error($t('shopProcess.emailErrorTips')))
  } else {
    callback()
  }
}

const validateTel = (rule, value, callback) => {
  if (value) {
    if (isTel(value)) {
      callback()
    } else {
      callback(new Error($t('shopProcess.telErrorTips')))
    }
  } else {
    callback()
  }
}

const shopBasicInfoRules = {
  firstLetter: [
    { required: true, message: '商城首字母不能为空', trigger: 'blur' }
  ],
  // merchantName: [
  //   { required: true, message: $t('shopProcess.merchantNameNotEmpty'), trigger: 'blur' },
  //   // { min: 2, max: 10, message: $t('shopProcess.merchantNameErrorTips'), trigger: 'blur' },
  //   { validator: validateNotEmpty, trigger: 'blur' }
  // ],
  shopName: [
    { required: true, message: $t('shopProcess.shopNameNotEmpty'), trigger: 'blur' },
    { min: 2, max: 20, message: $t('shopProcess.shopNameInputTips'), trigger: 'blur' },
    { validator: validateNotEmpty, trigger: 'blur' }
  ],
  tel: [
    { required: false, message: $t('shopProcess.telNotEmpty'), trigger: 'blur' },
    { validator: validateTel, trigger: 'blur' }
  ],
  shopLogo: [
    { required: true, message: $t('shopProcess.logoNotEmpty'), trigger: 'change' }
  ],
  merchantMail: [
    { required: false, message: $t('sys.emailaNoNull'), trigger: 'blur' },
    { validator: validateEmail, trigger: 'blur' }
  ],
  merchantPhone: [
    { validator: validateTel, trigger: 'blur' }
  ]
}

const endTimeFlag = ref(true)
const contractEndTimeFlag = ref(true)
// 商城签约信息
const signingInfo = reactive({
  contractStartTime: '', // 签约起始时间
  contractEndTime: '', // 签约终止时间
  type: '', // 商城类型 0普通商城 1优选商城
  mallVersion: 1,
  hasTry: 0
})
const pickerOptions = reactive({
  disabledDate (time) {
    const date = moment().add(0, 'days').startOf('days')
    return (
      time.getTime() >= date.valueOf()
    )
  }
})

const onValidateTime = (value) => {
  if (value === 'endTime') {
    endTimeFlag.value = true
    if (!companyInfoForm.value.startTime) companyInfoForm.value.endTime = undefined
  } else {
    endTimeFlag.value = false
    if (!companyInfoForm.value.startTime) companyInfoForm.value.endTime = undefined
  }
  if (companyInfoForm.value.endTime && Date.parse(companyInfoForm.value.startTime) >= Date.parse(companyInfoForm.value.endTime)) {
    ElMessage({
      message: $t('shopProcess.businessTimeTips'),
      type: 'error',
      duration: 1500
    })
    endTimeFlag.value = true
    companyInfoForm.value.endTime = undefined
  }
}

const companyInfoRule = reactive({
  creditCode: [
    { required: true, message: $t('shopProcess.creditCodeInputTips'), trigger: 'blur' },
    { validator: vaildCreditCode, trigger: 'blur' }
  ],
  firmName: [
    { required: true, message: $t('shopProcess.firmNameNotEmpty'), trigger: 'blur' }
  ],
  residence: [
    { validator: validateNotEmpty, trigger: ['blur', 'change'] }
  ],
  businessScope: [
    { required: true, message: $t('shopProcess.businessScopeNotEmpty'), trigger: 'blur' }
  ],
  businessLicense: [
    { required: true, message: $t('shopProcess.businessLicenseNotEmpty'), trigger: 'change' }
  ],
  representative: [
    { required: true, message: $t('shopProcess.representativeNotEmpty'), trigger: 'blur' }
    // { validator: validateNotEmptyRep, trigger: 'blur' }
  ],
  identityCardFront: [
    { required: true, message: $t('shopProcess.identityCardFrontNotEmpty'), trigger: 'change' }
  ],
  identityCardLater: [
    { required: true, message: $t('shopProcess.identityCardLaterNotEmpty'), trigger: 'change' }
  ],
  legalIds: [
    { required: true, message: '法人身份证不能为空', trigger: 'blur' },
    { validator: validIDCard, trigger: 'blur' }
  ],
  legalPhone: [
    { required: true, message: '法人手机号不能为空', trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ]
})

const bankCartInfoForm = reactive({
  data: [
    {
      bankName: '',
      recipientName: '',
      cardNo: '',
      branchName: '',
      accountNo: '', // 企业对公账户
      parentBankName: '', // 开户银行名称
      unionBank: '', // 支付行号 12位数字
      bankCardPro: 1 // 银行卡属性 0法人 1企业对公
    }
  ],
  rule: {
    bankName: [
      { required: true, message: '请填写开户支行名称', trigger: 'blur' },
      { min: 2, max: 20, message: '开户支行名称长度在2到20个字符', trigger: 'blur' },
      { validator: validateNotEmpty, trigger: 'blur' }
    ],
    cardNo: [
      { required: true, message: '账号不能为空', trigger: 'blur' },
      // { min: 1, max: 19, message: '账号长度在19个字符以内', trigger: 'blur' },
      { validator: validateNotEmpty, trigger: 'blur' }
      // { validator: validateCardNo, trigger: 'blur' }
    ],
    branchName: [
      { required: true, message: '支行名称不能为空', trigger: 'blur' },
      { min: 2, max: 20, message: '支行名称长度在2到20个字符', trigger: 'blur' },
      { validator: validateNotEmpty, trigger: 'blur' }
    ],
    accountNo: [
      { required: true, message: '请填写企业对公账户', trigger: 'blur' }
    ],
    parentBankName: [
      { required: true, message: '请填写开户银行名称', trigger: 'change' }
    ],
    unionBank: [
      { required: true, message: '请填写支付行号', trigger: 'blur' },
      { min: 12, max: 12, message: '请填写正确的支付行号', trigger: 'blur' }
    ]
  }
})

const selectBank = ref('') // 选择的银行，通联
const bankList = ref('') // 银行列表，通联
const submit = ref(false)
const statusRemarks = ref('')

const allinpayStore = useAllinpayStore()
const paySettlementType = computed(() => {
  return allinpayStore.paySettlementType
})

onMounted(() => {
  // 查询基本信息
  switchNav(0)
  // 商城审核状态
  queryShopAuditStatus()
})

const navStatus = ref(0)
const switchNav = (value) => {
  navStatus.value = value
  if (value === 1) {
    // 查询工商信息
    queryShopBusinessInfo()
  } else if (value === 2) {
    // 查询分类签约信息
    getSignCategoryList()
    // 查询品牌签约信息
    getSignBrandList()

    // 查询分类申请信息
    getSignCategoryList(0)
    // 查询品牌申请信息
    getSignBrandList(0)
  } else if (value === 3) {
    // 查询财务信息
    queryShopFinancialInfo()
  } else {
    // 查询基本信息
    queryShopBasicInfo()
  }
}

// 商城审核状态
const shopAuditStatus = ref({})
const shopId = route.query.shopId || 0
/**
 * 商城审核状态
 */
const queryShopAuditStatus = () => {
  http({
    url: http.adornUrl(`/shop/shopAuditing/${shopId}`),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    shopAuditStatus.value = data
  })
}

// 商城基本信息
const shopBasicInfo = ref({})
const companyInfo = ref({})
/**
 * 查询基本信息
 */
const queryShopBasicInfo = () => {
  http({
    url: http.adornUrl('/platform/shopDetail/info'),
    method: 'get',
    params: http.adornParams({
      shopId
    })
  }).then(({ data }) => {
    shopBasicInfo.value = data
    signingInfo.type = data.type
    signingInfo.contractStartTime = data.contractStartTime
    signingInfo.contractEndTime = data.contractEndTime
    signingInfo.hasTry = data.hasTry
    signingInfo.mallVersion = data.mallVersion
    shopStatus.shopStatus = data.shopStatus
    if (shopStatus.shopStatus === 6 && paySettlementType.value === 1) {
      statusRemarks.value = data.remarks || ''
      getauditInfor()
      getBankList()
    }
  })

  http({
    url: http.adornUrl('/platform/shopCompany'),
    method: 'get',
    params: http.adornParams({
      shopId
    })
  }).then(({ data }) => {
    companyInfo.value = data || {}
  })
}

// 获取工商信息的审核信息
const getauditInfor = () => {
  http({
    url: http.adornUrl('/platform/companyAuditing/auditInfo'),
    method: 'get',
    params: http.adornParams({
      shopId
    })
  }).then(({ data }) => {
    nextTick(() => {
      modifyInformation.value = { ...data.shopCompanyVO, ...data }
    })
  }).catch(res => {
  })
}

/**
 * 查询工商信息
 */
const queryShopBusinessInfo = () => {
  http({
    url: http.adornUrl('/platform/shopCompany'),
    method: 'get',
    params: http.adornParams({
      shopId
    })
  }).then(({ data }) => {
    companyInfoForm.value = data || {}
  })
}

const endTimeRef = ref(null)
const contractEndTimeRef = ref(null)
const focusEndTime = () => {
  endTimeRef.value?.focus()
  contractEndTimeRef.value?.focus()
}

/**
 * 注册资本输入框校验
 */
const changeNum = () => {
  const capital = companyInfoForm.value.capital
  companyInfoForm.value.capital = checkInput(capital)
  if (Number.parseFloat(companyInfoForm.value.capital) === 0) {
    companyInfoForm.value.capital = 0
  }
  if (Number.parseFloat(companyInfoForm.value.capital) > 99999999) {
    companyInfoForm.value.capital = 99999999
  }
}

/**
 * input输入框只允许输入正数和小数(保留小数点后两位)
 */
const checkInput = (num) => {
  if (num) {
    let tmpVal = num.replace(/[^\d^\\.]/g, '')
    const reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + ''
      tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
      const n = (tmpVal.split('.')).length - 1
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
      }
    }
    return tmpVal
  } else {
    return ''
  }
}

/**
 * 输入框不允许输入'-'或'+'
 */
const channelInputLimit = (e) => {
  const key = e.key
  if (key === '-' || key === '+') {
    e.returnValue = false
    return false
  }
  return true
}

// 商城分类签约信息
const signCategoryList = ref([])
/**
 * 签约类目列表
 */
const getSignCategoryList = (status = 1) => {
  http({
    url: http.adornUrl('/prod/category/signingInfoByShopId'),
    method: 'get',
    params: http.adornParams({
      shopId,
      status // 签约状态：1：已通过 0待审核 -1未通过
    })
  }).then(({ data }) => {
    if (data) {
      if (status === 1) {
        signCategoryList.value = data
        signCategoryList.value.forEach(item => {
          item.imgs = item.qualifications ? item.qualifications.split(',') : []
        })
      }
    }
  })
}

// 平台品牌签约信息
const signedBrands = ref([]) // 平台品牌+自定义品牌
/**
 * 获取签约品牌列表
 */
const getSignBrandList = (status = 1) => {
  http({
    url: http.adornUrl('/platform/brand/listSigningByShopId'),
    method: 'get',
    params: http.adornParams({
      shopId,
      status // 签约状态：1：已通过 0待审核 -1未通过
    })
  }).then(({ data }) => {
    if (status === 1) {
      signedBrands.value = data.platformBrandList
      signedBrands.value.forEach(el => {
        el.imgs = el.qualifications ? el.qualifications.split(',') : []
      })
    }
  })
}

const addSigningCategoryVisible = ref(false)
const addSigningCategoryRef = ref(null)
const addSigningBrandRef = ref(null)
const addSigningBrandVisible = ref(false)
/**
 * 编辑签约信息弹窗
 */
const addSigningHandle = (type) => {
  if (type === 0) {
    addSigningCategoryVisible.value = true
    nextTick(() => {
      addSigningCategoryRef.value?.init(shopId)
    })
    return
  }
  if (type === 1) {
    addSigningBrandVisible.value = true
    nextTick(() => {
      addSigningBrandRef.value?.init(shopId)
    })
  }
}

const cateAddOrUpdateVisible = ref(false)
const brandAddOrUpdateVisible = ref(false)
const cateAddOrUpdateRef = ref(null)
const brandAddOrUpdateRef = ref(null)
/**
 * 编辑签约信息弹窗
 * @param {Number} type 签约类型 0:类别 1:品牌
 */
const cateAddOrUpdateHandle = (type) => {
  if (type === 0) {
    cateAddOrUpdateVisible.value = true
    nextTick(() => {
      cateAddOrUpdateRef.value?.init(shopId)
    })
  } else if (type === 1) {
    brandAddOrUpdateVisible.value = true
    nextTick(() => {
      brandAddOrUpdateRef.value?.init(shopId)
    })
  }
}

/**
 * 关闭弹窗
 */
const closePopup = (val) => {
  if (val === 'category') {
    addSigningCategoryVisible.value = false
    cateAddOrUpdateVisible.value = false
    getSignCategoryList()

    // 查询分类申请信息
    getSignCategoryList(0)
  } else if (val === 'brand') {
    addSigningBrandVisible.value = false
    brandAddOrUpdateVisible.value = false
    getSignBrandList()
    // 查询品牌申请信息
    getSignBrandList(0)
  }
}

// 商城财务信息
const settlementAccounts = ref([])
/**
 * 查询财务信息
 */
const queryShopFinancialInfo = () => {
  http({
    url: http.adornUrl('/platform/shopBankCard/listByShopId'),
    method: 'get',
    params: http.adornParams({
      shopId
    })
  }).then(({ data }) => {
    settlementAccounts.value = data
    if (shopStatus.shopStatus === 6) {
      bankCartInfoForm.data = [{
        ...data[0],
        parentBankName: data[0].bankName,
        bankName: data[0].branchName,
        accountNo: data[0].bankCardNo
      }]
      selectBank.value = data[0].bankName
    }
  })
}

const shopBasicInfoRef = ref(null)
// 更新基本信息
const updateShopBasicInfo = () => {
  shopBasicInfoRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    http({
      url: http.adornUrl('/platform/shopDetail'),
      method: 'PUT',
      data: http.adornData(shopBasicInfo.value)
    }).then(() => {
      ElMessage({
        message: $t('shopProcess.baseInfoUpdateSuccess'),
        type: 'success',
        duration: 1000
      })
      queryShopBasicInfo()
    })
  })
}

const companyInfoFormRef = ref(null)
/**
 * 储存工商信息
 */
const updateCompanyInfo = () => {
  companyInfoForm.value.shopId = shopId
  companyInfoFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    http({
      url: http.adornUrl('/platform/shopCompany'),
      method: 'PUT',
      data: http.adornData(companyInfoForm.value)
    }).then(() => {
      ElMessage({
        message: $t('shopProcess.businessInfoUpdateSuccess'),
        type: 'success',
        duration: 1000
      })
      queryShopBusinessInfo()
    })
  })
}

let isSubmit = false
/**
 * 更新签约信息
 */
const updateSigningInfo = () => {
  if (paySettlementType !== 1) {
    if (!signingInfo.contractStartTime) {
      ElMessage({
        message: $t('shopProcess.contractValidityNotEmpty'),
        type: 'error',
        duration: 1000
      })
      return
    }
    if (signingInfo.contractEndTime && new Date(signingInfo.contractStartTime).getTime() > new Date(signingInfo.contractEndTime).getTime()) {
      ElMessage({
        message: $t('shopProcess.signingTimeTips'),
        type: 'error',
        duration: 1000
      })
      return
    }
  }
  if (isSubmit) {
    return
  }
  isSubmit = true
  signingInfo.shopId = shopId
  http({
    url: http.adornUrl('/platform/shopDetail/updateSigningInfo'),
    method: 'PUT',
    data: http.adornData(signingInfo)
  }).then(() => {
    ElMessage({
      message: $t('shopProcess.contractInfoUpdateSuccess'),
      type: 'success',
      duration: 1000
    })
    isSubmit = false
    // 更新签约信息成功后，需要更新商城基本信息，因为商城状态有可能发生改变
    queryShopBasicInfo()
  }).catch(() => {
    isSubmit = false
  })
}

// 获取可选银行名称列表（通联）
const getBankList = () => {
  http({
    url: http.adornUrl('/publicBank/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    bankList.value = data
  })
}
const changeBank = (value) => {
  bankCartInfoForm.data[0].parentBankName = value
}

const router = useRouter
const bankCartInfoFormRef = ref()
const toNextStep = () => {
  bankCartInfoFormRef.value.validate((valid) => {
    if (valid) {
      if (submit.value) {
        return
      }
      submit.value = true
      const data = {
        ...bankCartInfoForm.data[0],
        shopId
      }
      http({
        url: http.adornUrl('/platform/shopBankCard/allinpaySaveAndApplyShop'),
        method: 'post',
        data: http.adornData(data, false)
      }).then(() => {
        ElMessage({
          message: '提交成功！',
          type: 'success',
          duration: 1500,
          onClose: () => {
            router.push('/platform/shop-manage')
          }
        })
      }).finally(() => {
        submit.value = false
      })
    }
  })
}
// 签约有效期  结束时间处理
const contractEndTimeChange = (data) => {
  if (data) {
    nextTick(() => {
      signingInfo.contractEndTime = data.replace('00:00:00', '23:59:59')
    })
  }
}

const onChangeUse = (newValue, oldValue) => {
  ElMessageBox.confirm('确定修改是否试用吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    if (newValue == 1) {
      signingInfo.mallVersion = 3
      // signingInfo.contractStartTime = ''
      signingInfo.type = 0
    }
  }).catch(() => {
    signingInfo.hasTry = oldValue
  })
}

const onChangeVer = (newValue, oldValue) => {
  if (signingInfo.hasTry == 1) return
  ElMessageBox.confirm('确定修改商城版本吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    if (newValue != 3) {
      signingInfo.type = 0
    }
  }).catch(() => {
    signingInfo.mallVersion = oldValue
  })
}
</script>

<style lang="scss" scoped>
@use "index";
</style>
